package cz.muni.fi.pa165.web;

import cz.muni.restinterface.CourierDTO;
import cz.muni.restinterface.CustomerDTO;
import cz.muni.dto.ShipmentDTO;
import cz.muni.dto.TarrifDTO;
import cz.muni.service.CourierServiceLocal;
import cz.muni.service.CustomerServiceLocal;
import cz.muni.service.ShipmentServiceLocal;
import cz.muni.service.TarrifServiceLocal;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import javax.ejb.EJB;
import net.sourceforge.stripes.action.ActionBean;
import net.sourceforge.stripes.action.ActionBeanContext;
import net.sourceforge.stripes.action.Before;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.DontValidate;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.HandlesEvent;
import net.sourceforge.stripes.action.RedirectResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.UrlBinding;
import net.sourceforge.stripes.controller.LifecycleStage;
import net.sourceforge.stripes.validation.Validate;
import net.sourceforge.stripes.validation.ValidateNestedProperties;

/**
 *
 * @author Thomas
 */
@UrlBinding("/Manager-Shipment.{$event}")
public class ManagerShipmentActionBean implements ActionBean {

    @EJB(mappedName="java:global/DeliveryCompany-web/ShipmentService!cz.muni.service.ShipmentServiceLocal")
    private ShipmentServiceLocal shipmentService;
    @EJB(mappedName="java:global/DeliveryCompany-web/CustomerService!cz.muni.service.CustomerServiceLocal")
    private CustomerServiceLocal customerService;
    @EJB(mappedName="java:global/DeliveryCompany-web/CourierService!cz.muni.service.CourierServiceLocal")
    private CourierServiceLocal courierService;
    @EJB(mappedName="java:global/DeliveryCompany-web/TarrifService!cz.muni.service.TarrifServiceLocal")
    private TarrifServiceLocal tarrifService;
    private ActionBeanContext context;
    
    @ValidateNestedProperties({
        @Validate(field="weight", required=true),
        @Validate(field="distance", required=true),
    })
    private ShipmentDTO shipment;
    
    private Long senderID;
    private Long recipientID;
    private Long courierID;
    private Long tarrifID;

    public Long getSenderID() {
        return senderID;
    }

    public void setSenderID(Long senderID) {
        this.senderID = senderID;
    }

    public Long getRecipientID() {
        return recipientID;
    }

    public void setRecipientID(Long recipientID) {
        this.recipientID = recipientID;
    }

    public Long getCourierID() {
        return courierID;
    }

    public void setCourierID(Long courierID) {
        this.courierID = courierID;
    }

    public Long getTarrifID() {
        return tarrifID;
    }

    public void setTarrifID(Long tarrifID) {
        this.tarrifID = tarrifID;
    }
    
    private HashMap<Long,String> formatedDates = new HashMap<Long, String>();
    
    public HashMap getFormatedDates() {
        return formatedDates;
    }
    
    private void addFormattedDate(ShipmentDTO s) {
        if (s != null) {
            if (s.getId() != null && s.getCreationDate() != null) {
                formatedDates.put(s.getId(), new SimpleDateFormat("dd.MM.yyyy HH:mm").format(s.getCreationDate()));
            }
        }
    }

    public List<ShipmentDTO> getShipments() {
        List<ShipmentDTO> shipmnts = shipmentService.findAll();
        formatedDates.clear();
        for (ShipmentDTO s : shipmnts) addFormattedDate(s);
        return shipmnts;
    }

    public List<CustomerDTO> getCustomers() {
        return customerService.findAll();
    }
    
    public List<CourierDTO> getCouriers() {
        return courierService.findAll();
    }
    
    public List<TarrifDTO> getTarrifs() {
        return tarrifService.findAll();
    }

    public ShipmentDTO getShipment() {
        return shipment;
    }
    
    public void setShipment(ShipmentDTO shipment) {
        this.shipment = shipment;
    }
    
    @Override
    public void setContext(ActionBeanContext abc) {
        this.context = abc;
    }

    @Override
    public ActionBeanContext getContext() {
        return this.context;
    }
    
    @DefaultHandler
    public Resolution df() {
        return new ForwardResolution("/manager_shipments.jsp");
    }
    
  
    @HandlesEvent("add")
    public Resolution add() {
        CustomerDTO sender = customerService.find(senderID);
        CustomerDTO recipient = customerService.find(recipientID);
        CourierDTO courier = courierService.find(courierID);
        TarrifDTO tarrif = tarrifService.find(tarrifID);
        shipment.setCourier(courier);
        shipment.setSender(sender);
        shipment.setRecipient(recipient);
        shipment.setTarrif(tarrif);
        shipment.setCreationDate(new Date());
        shipment.setPrice(BigDecimal.valueOf(shipment.getDistance()*shipment.getWeight()));
        System.out.println(shipment);
        shipmentService.create(shipment);
        
        shipment.setTrackingNumber(Long.valueOf(new Long(shipment.getId() + Long.valueOf(1000)).hashCode()));
        shipmentService.update(shipment);
        
        
        return new RedirectResolution("/manager_shipments.jsp");
    }
    
    @DontValidate
    @Before(stages = LifecycleStage.BindingAndValidation, on = {"edit", "update"})
    public void loadShipmentFromDatabase() {
        String ids = context.getRequest().getParameter("shipment.id");
        if (ids == null) return;
        shipment = shipmentService.find(Long.parseLong(ids));
    }
 
    @DontValidate
    public Resolution edit() {
        return new ForwardResolution("/editShipment.jsp");
    }
 
    @DontValidate
    public Resolution update() {
        CustomerDTO sender = customerService.find(senderID);
        CustomerDTO recipient = customerService.find(recipientID);
        CourierDTO courier = courierService.find(courierID);
        TarrifDTO tarrif = tarrifService.find(tarrifID);
        shipment.setCourier(courier);
        shipment.setSender(sender);
        shipment.setRecipient(recipient);
        shipment.setTarrif(tarrif);
        shipment.setPrice(BigDecimal.valueOf(shipment.getDistance()*shipment.getWeight()));
        shipmentService.update(shipment);
        return new RedirectResolution("/manager_shipments.jsp");
    }
    
    @DontValidate
    public Resolution delete() {
        shipmentService.delete(shipment);
        return new RedirectResolution("/manager_shipments.jsp");
    }
}
